#include <QApplication>
#include <QCoreApplication>
#include <QDebug>
#include <QTimer>
#include <QProcess>
#include <QWindow>
#include <QMessageBox>


#include "DesktopActivator.h"
#include "WallPaper.h"
#include <signal.h>

static QProcess *videoDesktop = nullptr;

void onReceivedSignal(int sig)
{
    qInfo() << "Received Signal " << sig;
    // 正常退出前执行清理动作
    qApp->exit(1);
}


int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_DisableHighDpiScaling);
    QApplication a(argc, argv);
    QString videoPath;
    if (argc == 2)
    {
        videoPath = argv[1];
    }
    else
    {
        // set the default video
        videoPath = "/usr/share/dde-introduction/community.mp4";
        qInfo() << "Usage: ./video xxx.mp4";
    }

    QMessageBox msgBox;
    QString msg;

    WallPaper w;
    if (w.setVideo(videoPath))
    {
        w.show();
        w.play();
    }
    else
    {
        msg = "Cannot load video " + videoPath;
        qWarning() << msg;
        msgBox.setText(msg);
        msgBox.exec();
        return 1;
    }

    videoDesktop = new QProcess;
    videoDesktop->setStandardOutputFile(QProcess::nullDevice());
    videoDesktop->setStandardErrorFile(QProcess::nullDevice());
    QString program = QCoreApplication::applicationDirPath() + "/dde-desktop";

    QTimer::singleShot(1000, &w, [&](){
        // 友好的CloseEvent关闭dde-desktop
        system("xdotool search --class dde-desktop  windowkill");

        // 带参数启动修改后的dde-desktop
        QStringList args;
        args << "--video-wallpaper" << QString::number(w.windowHandle()->winId());
        videoDesktop->start(program, args);

    });

    QObject::connect(videoDesktop, &QProcess::errorOccurred, &w, [&](){
        msg = QString("Cannot execute %1 \n\n %2 ").arg(program).arg(videoDesktop->errorString());
        qWarning() << msg;
        msgBox.setText(msg);
        msgBox.exec();
        qApp->exit(2);
    });

    // 必要时激活dde-desktop
    DesktopActivator DA;
    QTimer::singleShot(2000, &w, [&w, &DA](){
        w.installEventFilter(&DA);
    });

    // 接受信号时退出程序
    signal(SIGTERM, onReceivedSignal);
    signal(SIGINT, onReceivedSignal);

    int res = a.exec();

    // 友好的CloseEvent关闭dde-desktop
    system("xdotool search --class dde-desktop  windowkill");
    qInfo() << "Close dde-desktop";

    // 启动正常的dde-desktop
    system("/usr/bin/dde-desktop > /dev/null 2>&1 &");
    qInfo() << "Start dde-desktop";

    return res;
}
